package v1

import (
	"yuanxin-admin/internal/common"
	"yuanxin-admin/internal/repository"

	"gitee.com/botaoshow/yuanxin/web/common/database"
	"gitee.com/botaoshow/yuanxin/web/response"
	"github.com/gin-gonic/gin"
)

type SysController struct {
}

func NewSysController() *SysController {
	return &SysController{}
}

func (s *SysController) WebInfo(c *gin.Context) {
	if list, err := repository.SysWebsite.WithContext(c).
		Order(repository.SysWebsite.ID.Desc()).Find(); err != nil {
		response.Fail(c, err.Error())
	} else {
		response.Success(c, list)
	}
}

func (s *SysController) WebInfoQuery(c *gin.Context) {
	if list, err := repository.SysWebsite.WithContext(c).
		Order(repository.SysWebsite.ID.Desc()).Find(); err != nil {
		response.Fail(c, err.Error())
	} else {
		response.Success(c, list)
	}
}

func (s *SysController) WebInfoSync(c *gin.Context) {
	var reqDto struct {
		KeyName      string `json:"keyName"`
		SettingValue string `json:"settingValue"`
	}
	if err := c.ShouldBindBodyWithJSON(&reqDto); err != nil {
		response.Fail(c, err.Error())
		return
	}
	resultInfo, err := repository.SysWebsite.WithContext(c).
		Where(repository.SysWebsite.KeyName.Eq(reqDto.KeyName)).
		Update(repository.SysWebsite.SettingValue, reqDto.SettingValue)
	if err != nil {
		response.Fail(c, err.Error())
	} else {
		response.Success(c, resultInfo)
	}
}

func (s *SysController) WebInfoSyncBatch(c *gin.Context) {
	var reqDto []struct {
		KeyName      string `json:"keyName"`
		SettingValue string `json:"settingValue"`
	}
	if err := c.ShouldBindBodyWithJSON(&reqDto); err != nil {
		response.Fail(c, err.Error())
		return
	}
	//开启事务
	q := repository.Use(database.Db)
	err := q.Transaction(func(tx *repository.Query) error {
		for _, v := range reqDto {
			_, err := tx.SysWebsite.WithContext(c).
				Where(tx.SysWebsite.KeyName.Eq(v.KeyName)).
				Update(tx.SysWebsite.SettingValue, v.SettingValue)
			if err != nil {
				return err
			}
		}
		return nil
	})
	if err != nil {
		response.Fail(c, err.Error())
		return
	}
	response.SuccessDefault(c)
}

func (s *SysController) GetRsaPublicKey(c *gin.Context) {
	response.Success(c, common.DefaultRsaPublicKey)
}
